package com.zeng.stpro.modules.security.handler;

import com.zeng.stpro.commons.utils.JwtUtils;
import com.zeng.stpro.commons.utils.R;
import com.zeng.stpro.commons.utils.ResponseUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author ZENGZHIJUN
 * @Date 2021/2/4 16:29
 */

public class TokenLogoutHandler implements LogoutHandler {
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1 从header里面获取token
        //2 token不为空，移除token，从redis删除token
        String token = request.getHeader("token");
        if(token != null) {
            //从token获取用户名
            String username = JwtUtils.parseToken(token);
            //redis中删除
            redisTemplate.delete(username);
            //移除
            JwtUtils.removeToken(token);
        }
        ResponseUtils.out(response, R.ok());
    }
}